<template>
    <ElDialog v-model="dialogVisible" width="600px" :title="title">
        <UiForm :formData="formData" @close="dialogVisible = false" @callback="submitForm"/>
    </ElDialog>
</template>
<script setup>
import {ElDialog, ElMessage } from 'element-plus'
import UiForm from '@/components/uiForm.vue'
import { computed, ref, reactive, onMounted } from 'vue';
import {setUser, getRoleList, getUserListInfo} from '@/server/manage/sys.js'
import { isEmail, validateMobile } from '@/utils/validate'

const props = defineProps(['modelValue', 'type', 'info'])
const emit = defineEmits(['update:modelValue', 'callback'])
const options = ref([
    {label: '禁用', value: 0},
    {label: '正常', value: 1}
])
const roleList = ref([])
// 确认密码校验
const validatePass = (rule, value, callback) => {
    let dataForm = paramsData()
    if (props.type === 'add' && !/\S/.test(value)) {
        callback(new Error('确认密码不能为空'))
    } else if (dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
    } else {
        callback()
    }
}
// 邮箱校验
const  validateEmail = (rule, value, callback) => {
    if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
    } else {
        callback()
    }
}
const formData = reactive([
    {label: "用户名", type: 'input',key: "username", value: '', required: true},
    {label: "密码", type: 'input', widgetType: "password", key: "password", value: '', required: props.type === 'add'},
    {label: "确认密码", type: 'input', widgetType: "password", key: "comfirmPassword", value: '',required: props.type === 'add', rules: { validator: validatePass, trigger: 'blur' }},
    {label: "邮箱", type: 'input',key: "email", value: '', required: true, rules: { validator: validateEmail, trigger: 'blur' }},
    {label: "手机号", type: 'input',key: "mobile", value: '', required: true, rules: { validator: validateMobile, trigger: 'blur' }},
    {label: "角色", type: 'checkbox', key: "roleIdList", value: [], required: false, options: roleList},
    {label: "状态", type: 'radio', key: "status", value: 1, required: true, options: options}
])
// 获取表单数据
const paramsData = () => {
    return formData.reduce((obj,item) => {
        obj[item.key] = item.value
        return obj
    },{})
}
const dialogVisible = computed({
    set:(val) => {
        emit('update:modelValue', val)
    },
    get:() => {
        return props.modelValue
    }
})
const title = computed(() => {
    let obj = {add: '新增',edit: '编辑' }
    return obj[props.type]
})
// 提交
const submitForm = (formData) => {
    let obj = {add: 'save',edit: 'update' }
    let apiData = formData
    apiData.userId = props.info?.userId || undefined
    apiData.salt = props.info?.salt || ''



    setUser(apiData, obj[props.type]).then(res => {
        dialogVisible.value = false
        emit('callback')
        ElMessage({ message: "操作成功！", type: 'success'})
    })
}
// 获取详情
const getDetail = () => {
    getUserListInfo(props.info?.userId).then(res => {
        console.log(res.user);
        let userInfo = res.user
        let list = ['username', 'email', 'mobile', 'roleIdList', 'status']
        formData.forEach(item => {
            if(list.includes(item.key)){
                item.value = userInfo[item.key]
            }
        })
    })
}
// 获取角色列表
const getRoles = () => {
    getRoleList().then(res => {
        roleList.value = res.list.map(item => {
          return {label: item.roleName, value: item.roleId}
        })
    })
}
onMounted(() => {
    getRoles()
    if(props.type === 'edit') {getDetail()}
})
</script>